﻿using System;
using System.Windows.Forms;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Win32;
using Microsoft.WowAddonStudio.Setup.CustomActions.Properties;
using System.IO;

namespace Microsoft.WowAddonStudio.Setup.CustomActions
{
    public class CustomAction
    {
        private const string visualStudioHiveKeyName = @"SOFTWARE\Microsoft\VisualStudio\9.0";
        private const string visualStudioInstallDirName = "InstallDir";
        private const string schemaRelativePath = "Xml/Schemas";

        static CustomAction()
        {
            Application.EnableVisualStyles();
        }

        [CustomAction]
        public static ActionResult DetectWowInstallation(Session session)
        {
            session.Log("Begin DetectWowInstallation");

            if (!WowManager.IsWowInstalled)
            {
                session.Log("World of Warcraft installation not detected.");

                if (MessageBox.Show(null, "A World of Warcraft installation was not detected. It is recommended that your first install World of Warcraft.\nWould you like to continue with the installation?", 
                                    "AddOn Studio for World of Warcraft Setup", 
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                {
                    session.Log("User opted out of installation.");
                    return ActionResult.UserExit;
                }
            }

            return ActionResult.Success;
        }

        [CustomAction]
        public static ActionResult ExtractUiXsd(Session session)
        {
            session.Log("Begin ExtractUiXsd");

            // Create MPQ extractor using the Windows Installer session
            var mpqExtractor = new MpqExtractor(new WindowsInstallerSession(session));

            // Check whether WoW is available
            if (!WowManager.IsWowInstalled)
            {
                session.Log("World of Warcraft installation not detected.");
                return ActionResult.NotExecuted;
            }

            // Get the locale(s) installed for WoW
            string[] locales = WowManager.GetLocales();

            if (locales == null)
            {
                session.Log("Could not detect locales.");
                return ActionResult.NotExecuted;
            }

            session.Log("Locale Count: {0}", locales.Length);

            if (locales.Length > 0)
            {
                string locale = locales[0];
                session.Log("Using Locale: {0}", locale);

                string mpqRelativePath = WowManager.GetLocalizedMpqPath(Settings.Default.LocalizedMpqBaseName, locale);
                string destinationFolder = CustomAction.GetVisualStudioInstallDir();

                if (String.IsNullOrEmpty(destinationFolder))
                {
                    session.Log("Could not detect Visual Studio 2008 install directory.");
                    return ActionResult.NotExecuted;
                }

                destinationFolder = Path.Combine(destinationFolder, schemaRelativePath);
                mpqExtractor.ExtractFromMpq(mpqRelativePath, Settings.Default.UiXsdPath, destinationFolder);
            }

            return ActionResult.Success;
        }

        private static string GetVisualStudioInstallDir()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(visualStudioHiveKeyName))
            {
                if (key != null)
                {
                    var visualStudioInstallDir = (string)key.GetValue(visualStudioInstallDirName, null);

                    // Walk up two folders on the directory hierarchy
                    if (visualStudioInstallDir != null)
                    {
                        // Remove trailing backslash
// ReSharper disable PossibleNullReferenceException
                        return Directory.GetParent(visualStudioInstallDir.TrimEnd('\\')).Parent.FullName;
// ReSharper restore PossibleNullReferenceException
                    }
                }
            }

            return null;
        }
    }
}